<template>

    <Head @selectDate="selectDate"></Head>
    <div class="recordDiet">
        <van-pull-refresh v-model="loading" @refresh="onRefresh">
            <van-collapse class="cardList" v-model="activeNames">
                <van-collapse-item class="breakfast card" title="早餐" name="1">
                    <div class="input">
                        <input v-model="breakfast" type="text" placeholder="请添加食物名称与数量">
                        <van-button color="#3176FF" @click="addFood(breakfast, '早餐')" class="btn" type="primary"
                            size="small">添加</van-button>
                    </div>
                    <ul class="mealList">
                        <li v-for="item in breakfastList">
                            <span>{{ item.mealName }}</span>
                            <van-button color="#3176FF" class="btn" type="primary" size="small"
                                @click="deleteData(item.id)">删除</van-button>
                        </li>
                    </ul>
                    <div class="nutrition">
                        <p>营养摄入</p>
                        <ul>
                            <li>
                                <div>
                                    <label>热量</label>
                                    <span>{{ breakfastList.reduce((pre, item) => {
                                        return pre + item.calorie
                                    }, 0) }} kcal</span>
                                </div>
                                <van-progress color="#3176FF " track-color="#E5E7EB" stroke-width="10px" pivot-text=""
                                    class="progressBar" :percentage="(breakfastList.reduce((pre, item) => {
                                        return pre + item.calorie
                                    }, 0)) / 7" />
                            </li>
                            <li>
                                <div>
                                    <label>蛋白质</label>
                                    <span>{{ breakfastList.reduce((pre, item) => {
                                        return pre + item.protein
                                    }, 0) }} g</span>
                                </div>
                                <van-progress color="#4CAF50 " track-color="#E5E7EB" stroke-width="10px" pivot-text=""
                                    class="progressBar" :percentage="(breakfastList.reduce((pre, item) => {
                                        return pre + item.protein
                                    }, 0)) / 30 * 100" />
                            </li>
                        </ul>
                    </div>
                </van-collapse-item>
                <van-collapse-item class="lunch card" title="午餐" name="2">
                    <div class="input">
                        <input v-model="lunch" type="text" placeholder="请添加食物名称与数量">
                        <van-button color="#3176FF" @click="addFood(lunch, '午餐')" class="btn" type="primary"
                            size="small">添加</van-button>
                    </div>
                    <ul class="mealList">
                        <li v-for="item in lunchList">
                            <span>{{ item.mealName }}</span>
                            <van-button color="#3176FF" class="btn" type="primary" size="small"
                                @click="deleteData(item.id)">删除</van-button>
                        </li>
                    </ul>
                    <div class="nutrition">
                        <p>营养摄入</p>
                        <ul>
                            <li>
                                <div>
                                    <label>热量</label>
                                    <span>{{ lunchList.reduce((pre, item) => {
                                        return pre + item.calorie
                                    }, 0) }} kcal</span>
                                </div>
                                <van-progress color="#3176FF " track-color="#E5E7EB" stroke-width="10px" pivot-text=""
                                    class="progressBar" :percentage="(lunchList.reduce((pre, item) => {
                                        return pre + item.calorie
                                    }, 0)) / 15" />
                            </li>
                            <li>
                                <div>
                                    <label>蛋白质</label>
                                    <span>{{ lunchList.reduce((pre, item) => {
                                        return pre + item.protein
                                    }, 0) }} g</span>
                                </div>
                                <van-progress color="#4CAF50 " track-color="#E5E7EB" stroke-width="10px" pivot-text=""
                                    class="progressBar" :percentage="(lunchList.reduce((pre, item) => {
                                        return pre + item.protein
                                    }, 0)) / 50 * 100" />
                            </li>
                        </ul>
                    </div>
                </van-collapse-item>
                <van-collapse-item class="dinner card" title="晚餐" name="3">
                    <div class="input">
                        <input v-model="dinner" type="text" placeholder="请添加食物名称与数量">
                        <van-button color="#3176FF" @click="addFood(dinner, '晚餐')" class="btn" type="primary"
                            size="small">添加</van-button>
                    </div>
                    <ul class="mealList">
                        <li v-for="item in dinnerList">
                            <span>{{ item.mealName }}</span>
                            <van-button color="#3176FF" class="btn" type="primary" size="small"
                                @click="deleteData(item.id)">删除</van-button>
                        </li>
                    </ul>
                    <div class="nutrition">
                        <p>营养摄入</p>
                        <ul>
                            <li>
                                <div>
                                    <label>热量</label>
                                    <span>{{ dinnerList.reduce((pre, item) => {
                                        return pre + item.calorie
                                    }, 0) }} kcal</span>
                                </div>
                                <van-progress color="#3176FF " track-color="#E5E7EB" stroke-width="10px" pivot-text=""
                                    class="progressBar" :percentage="(dinnerList.reduce((pre, item) => {
                                        return pre + item.calorie
                                    }, 0)) / 9" />
                            </li>
                            <li>
                                <div>
                                    <label>蛋白质</label>
                                    <span>{{ dinnerList.reduce((pre, item) => {
                                        return pre + item.protein
                                    }, 0) }} g</span>
                                </div>
                                <van-progress color="#4CAF50 " track-color="#E5E7EB" stroke-width="10px" pivot-text=""
                                    class="progressBar" :percentage="(dinnerList.reduce((pre, item) => {
                                        return pre + item.protein
                                    }, 0)) / 40 * 100" />
                            </li>
                        </ul>
                    </div>
                </van-collapse-item>
                <van-collapse-item class="snack card" title="加餐" name="4">
                    <div class="input">
                        <input v-model="snack" type="text" placeholder="请添加食物名称与数量">
                        <van-button color="#3176FF" @click="addFood(snack, '加餐')" class="btn" type="primary"
                            size="small">添加</van-button>
                    </div>
                    <ul class="mealList">
                        <li v-for="item in snackList">
                            <span>{{ item.mealName }}</span>
                            <van-button color="#3176FF" class="btn" type="primary" size="small"
                                @click="deleteData(item.id)">删除</van-button>
                        </li>
                    </ul>
                    <div class="nutrition">
                        <p>营养摄入</p>
                        <ul>
                            <li>
                                <div>
                                    <label>热量</label>
                                    <span>{{ snackList.reduce((pre, item) => {
                                        return pre + item.calorie
                                    }, 0) }} kcal</span>
                                </div>
                                <van-progress color="#3176FF " track-color="#E5E7EB" stroke-width="10px" pivot-text=""
                                    class="progressBar" :percentage="(snackList.reduce((pre, item) => {
                                        return pre + item.calorie
                                    }, 0)) / 4" />
                            </li>
                            <li>
                                <div>
                                    <label>蛋白质</label>
                                    <span>{{ snackList.reduce((pre, item) => {
                                        return pre + item.protein
                                    }, 0) }} g</span>
                                </div>
                                <van-progress color="#4CAF50 " track-color="#E5E7EB" stroke-width="10px" pivot-text=""
                                    class="progressBar" :percentage="(snackList.reduce((pre, item) => {
                                        return pre + item.protein
                                    }, 0)) / 30 * 100" />
                            </li>
                        </ul>
                    </div>
                </van-collapse-item>
            </van-collapse>
            <div class="todayTatal">
                <div class="title">今日总计</div>
                <div class="tatal">
                    <div class="calorie">
                        <label>总热量</label>
                        <span>{{ foodList.reduce((pre, item) => {
                            return pre + item.calorie
                        }, 0) }} kcal</span>
                    </div>
                    <van-progress color="#3176FF" track-color="#E5E7EB" stroke-width="10px" pivot-text=""
                        class="progressBar" :percentage="(foodList.reduce((pre, item) => {
                            return pre + item.calorie
                        }, 0)) / 20" />
                    <div class="type">
                        <span>蛋白质: {{ (foodList.reduce((pre, item) => {
                            return pre + item.protein
                        }, 0)).toFixed(1) }}g</span>
                        <span>脂肪: {{ foodList.reduce((pre, item) => {
                            return pre + item.fat
                        }, 0) }}g</span>
                        <span>碳水: {{ foodList.reduce((pre, item) => {
                            return pre + item.carbon
                        }, 0) }}g</span>
                    </div>
                    <div class="echarts" ref="echartsRef"></div>
                </div>
            </div>
        </van-pull-refresh>
    </div>
    <van-popup v-model:show="show" position="bottom" round>
        <van-time-picker v-model="currentTime" title="选择时间" @confirm="confirm" @cancel="cancel" />
    </van-popup>
</template>

<script setup>
import Head from '@/components/Head.vue'
import { ref, onMounted } from 'vue'
import { showSuccessToast, showFailToast } from 'vant';
import { getDietData, getFoodComponent, writeFoodData, deleteFoodData } from '@/api/index.js'
import * as echarts from 'echarts/core';
import { TooltipComponent, LegendComponent } from 'echarts/components';
import { PieChart } from 'echarts/charts';
import { LabelLayout } from 'echarts/features';
import { CanvasRenderer } from 'echarts/renderers';
import { showConfirmDialog } from 'vant';


echarts.use([
    TooltipComponent,
    LegendComponent,
    PieChart,
    CanvasRenderer,
    LabelLayout
]);


const activeNames = ref([])
const time = ref((new Date(new Date().setHours(8, 0, 0, 0)).getTime()).toString())
const breakfastList = ref([])
const lunchList = ref([])
const dinnerList = ref([])
const snackList = ref([])
const foodList = ref([])
const echartsRef = ref('')
const breakfast = ref('')
const lunch = ref('')
const dinner = ref('')
const snack = ref('')
const component = ref({})
const show = ref(false)
const currentTime = ref([])
const loading = ref(false);


onMounted(async () => {
    await getDayData()
})

// 下拉刷新
const onRefresh = async () => {
    await getDayData()
    showSuccessToast('刷新成功');
    loading.value = false;
};

// 选择日期
const selectDate = async (type) => {
    time.value = (new Date(type.join('-')).getTime()).toString()
    await getDayData()
    showSuccessToast('切换成功')
}

// 获取一天的餐食
const getDayData = async () => {
    const res = await getDietData(time.value)
    foodList.value = res.data
    breakfastList.value = []
    lunchList.value = []
    dinnerList.value = []
    snackList.value = []
    // console.log(foodList.value);
    res.data.forEach(item => {
        if (item.mealType === '早餐') {
            breakfastList.value.push(item)
        } else if (item.mealType === '午餐') {
            lunchList.value.push(item)
        } else if (item.mealType === '晚餐') {
            dinnerList.value.push(item)
        } else {
            snackList.value.push(item)
        }
    });
    loadChart(foodList.value)
}

// 获取食物的营养成分
const addFood = async (foodType, mealType) => {
    // console.log(foodType);
    if (foodType) {
        const res = await getFoodComponent(foodType)
        component.value = JSON.parse(res.data)
        component.value.mealName = foodType
        component.value.mealType = mealType
        // console.log(component.value);
        show.value = true
    } else {
        showFailToast('请先输入食物名称与数量')
    }
}

// 写入一条食物数据
const confirm = async () => {
    // writeFoodData
    // console.log(currentTime.value.join(':'));
    const res = await writeFoodData({ component: component.value, time: currentTime.value.join(':'), create_time: time.value })
    // console.log(res);
    showSuccessToast(res.msg)
    await getDayData()
    breakfast.value = ''
    lunch.value = ''
    dinner.value = ''
    snack.value = ''
    show.value = false
}

const cancel = () => {
    show.value = false
}

// 删除一条食物数据
const deleteData = (id) => {
    // console.log(id);
    showConfirmDialog({
        message:
            '您确认要删除这条数据吗？',
    })
        .then(async () => {
            const res = await deleteFoodData(id)
            showSuccessToast(res.msg)
            await getDayData()
        })
        .catch(() => {
            // on cancel
        });
}

// echarts
const loadChart = (foodList) => {
    const myChart = echarts.init(echartsRef.value);
    const protein = foodList.reduce((pre, item) => {
        return pre + item.protein
    }, 0)
    const fat = foodList.reduce((pre, item) => {
        return pre + item.fat
    }, 0)
    const carbon = foodList.reduce((pre, item) => {
        return pre + item.carbon
    }, 0)

    const option = {
        tooltip: {
            trigger: 'item'
        },
        legend: {
            top: '5%',
            left: 'center'
        },
        series: [
            {
                name: 'Access From',
                type: 'pie',
                radius: ['40%', '70%'],
                avoidLabelOverlap: false,
                padAngle: 5,
                itemStyle: {
                    borderRadius: 10
                },
                label: {
                    show: false,
                    position: 'center'
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: 40,
                        fontWeight: 'bold'
                    }
                },
                labelLine: {
                    show: false
                },
                data: [
                    { value: protein, name: '蛋白质' },
                    { value: fat, name: '脂肪' },
                    { value: carbon, name: '碳水' },
                ]
            }
        ]
    };

    option && myChart.setOption(option);

}
</script>

<style lang="less" scoped>
.recordDiet {
    padding: .4267rem;
    box-sizing: border-box;
    width: 100%;
    height: calc(100vh - 2.5347rem);
    overflow: scroll;
    background: #F9FAFB;

    .card {
        margin-bottom: 0.43rem;
        box-shadow: 0px 4px 6px -1px rgba(0, 0, 0, 0.1), 0px 2px 4px -2px rgba(0, 0, 0, 0.1);
        border-radius: 0.32rem;

        :deep(.van-cell) {
            padding: 16px;
        }

        :deep(.van-cell__title) {
            display: inline-block;
            font-weight: 500;
            font-size: 0.48rem;
            color: #000000;
            line-height: 0.75rem;
        }

        .input {
            display: flex;
            align-items: center;
            margin-bottom: .2133rem;

            input {
                flex: 1;
                box-sizing: border-box;
                font-weight: 400;
                font-size: 0.37rem;
                color: #9CA3AF;
                line-height: 0.56rem;
                padding: .2133rem;
                border-radius: 4px 2px 2px 4px;
                border: 1px solid #D1D5DB;
            }

            :deep(.btn) {
                width: 1.6rem;
                height: 0.99rem;
            }
        }

        .mealList {
            li {
                display: flex;
                align-items: center;
                justify-content: space-between;
                border-bottom: 1px solid #E5E7EB;
                margin-bottom: .2133rem;

                span {
                    font-weight: 400;
                    font-size: 0.37rem;
                    color: #000000;
                    line-height: 0.56rem;
                }

                :deep(.btn) {
                    width: 1.6rem;
                    height: 0.99rem;
                }
            }
        }

        .nutrition {
            p {
                font-weight: 600;
                font-size: 0.37rem;
                color: #000000;
                line-height: 0.56rem;
                margin-bottom: .2133rem;
            }

            ul {
                li {
                    div {
                        display: flex;
                        justify-content: space-between;
                        align-items: center;
                        font-weight: 400;
                        font-size: 14px;
                        color: #000000;
                        line-height: 21px;
                        margin-bottom: .2133rem;
                    }
                }
            }
        }
    }

    .todayTatal {
        background-color: #fff;

        .title {
            font-weight: 600;
            font-size: 0.37rem;
            color: #000000;
            line-height: 0.56rem;
        }

        .tatal {
            padding: .4267rem;
            box-shadow: 0px 4px 6px -1px rgba(0, 0, 0, 0.1), 0px 2px 4px -2px rgba(0, 0, 0, 0.1);
            border-radius: .32rem;

            .calorie {
                display: flex;
                justify-content: space-between;
                align-items: center;
                font-weight: 400;
                font-size: 0.37rem;
                color: #000000;
                line-height: 0.56rem;
                margin-bottom: .2133rem;
            }

            .progressBar {
                margin-bottom: 0.43rem;
            }

            .type {
                display: flex;
                margin-bottom: .4267rem;

                span {
                    flex: 1;
                    text-align: center;
                    font-weight: 400;
                    font-size: 0.37rem;
                    color: #4B5563;
                    line-height: 0.53rem;
                }
            }

            .echarts {
                width: 100%;
                height: 5.33rem;
            }
        }
    }
}
</style>